<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="24">
          <el-col :span="12">
            <el-form-item label="单位名称" prop="custName">
              <el-input class="input-item" v-model="ruleForm.custName" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户层级" prop="custLevel">
              <el-select v-model="ruleForm.custLevel" placeholder="请选择">
                <el-option v-for="(item,index) in hierarchylist" :key="index"
                :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位属性" prop="unitAttribute">
              <el-select v-model="ruleForm.unitAttribute" placeholder="请选择">
                <el-option label="国有企业" :value="1"></el-option>
                <el-option label="国有控股企业" :value="2"></el-option>
                <el-option label="外资企业" :value="3"></el-option>
                <el-option label="合资企业" :value="4"></el-option>
                <el-option label="私营企业" :value="5"></el-option>
                <el-option label="事业单位" :value="6"></el-option>
                <el-option label="国家行政机关" :value="7"></el-option>
                <el-option label="其他" :value="8"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户地区" prop="districtCode">
              <el-cascader v-model="ruleForm.districtCode"
                ref="ref_customerareaCodes"
                :options="areaCodelist"
                :props="areaCodeprops"
                :show-all-levels="false"
                clearable
                @change="customerareaCodesChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业联系人" prop="contacts">
              <el-input class="input-item" v-model="ruleForm.contacts" placeholder="请输入" maxlength="8"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="telephone">
              <el-input class="input-item" v-model="ruleForm.telephone" placeholder="请输入" maxlength="11" type='tel' onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户职务" prop="custPosition">
              <el-input class="input-item" v-model="ruleForm.custPosition" placeholder="请输入" maxlength="10"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户生日">
              <el-date-picker v-model="ruleForm.custBirthday" type="date" placeholder="选择日期"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户兴趣">
              <el-input class="input-item" v-model="ruleForm.custInterest" placeholder="请输入" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护周期">
              <el-input class="input-item" v-model="ruleForm.maintainCycle" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主要社会关系">
              <el-input type="textarea" class="input-item" v-model="ruleForm.mainSocialRelations" placeholder="请输入" maxlength="80"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0;">
              <el-button size="mini" @click="onCancel(false)">取消</el-button>
              <el-button type="primary" size="mini" @click="submitForm()">确定</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Customers } from '@/api/commercial.js';
import { EcologicalkKnowledge } from '@/api/knowledgeBases.js';
export default {
  name: 'Customeradd',
  props: {
    customerId: {
      default: undefined
    }
  },
  data () {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入'))
      } else {
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      loading: false,
      isShowloading: false,
      userId: null,
      customerareaCodes: [],
      areaCodelist: [],
      areaCodeprops: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      customerlist: [],
      hierarchylist: [],
      situation: 1,
      ruleForm: {
        custName: '',
        custLevel: '',
        unitAttribute: '',
        districtCode: '',
        contacts: '',
        telephone: '',
        custPosition: '',
        custBirthday: '',
        custInterest: '',
        maintainCycle: '',
        mainSocialRelations: ''
      },
      rules: {
        custName: [{ required: true, message: '请输入', trigger: 'blur' }],
        custLevel: [{ required: true, message: '请选择', trigger: 'change' }],
        unitAttribute: [{ required: true, message: '请输入', trigger: 'blur' }],
        districtCode: [{ required: true, message: '请选择', trigger: 'change' }],
        contacts: [{ required: true, message: '请输入', trigger: 'blur' }],
        telephone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        custPosition: [{ required: true, message: '请输入', trigger: 'blur' }],
        isBid: [{ required: true, message: '请选择', trigger: 'blur' }],
        director: [{ required: true, message: '请选择', trigger: 'blur' }],
        contractAmount: [{ required: true, message: '请输入', trigger: 'blur' }],
        tradingDate: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    };
  },
  created () {
  },
  computed: {
    isEdit () {
      return this.customerId != null && this.customerId !== '';
    }
  },
  mounted () {
    if (this.isEdit) {
      this.loadCustomerdetail()
    } else {
      this.loadareaCodelistDict()
      this.loadCustomerList()
      this.loadHierarchyList()
    }
  },
  methods: {
    /**
     * 客户详情
     */
    loadCustomerdetail () {
      let params = this.customerId
      return new Promise((resolve, reject) => {
        Customers.detail(this, params).then(res => {
          this.ruleForm = res.data
          this.ruleForm.districtCode = parseInt(res.data.districtCode)
          this.loadareaCodelistDict()
          this.loadCustomerList()
          this.loadHierarchyList()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 客户列表
     */
    loadCustomerList () {
      let params = ''
      return new Promise((resolve, reject) => {
        Customers.lists(this, params).then(res => {
          this.customerlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 客户层级
     */
    loadHierarchyList () {
      let params = ''
      return new Promise((resolve, reject) => {
        Customers.hierarchy(this, params).then(res => {
          this.hierarchylist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 行政区划
     */
    loadareaCodelistDict () {
      return new Promise((resolve, reject) => {
        EcologicalkKnowledge.listDict(this).then(res => {
          let areaCodelist = res.data
          let areaCodelistnew = []
          areaCodelist.forEach((item, index) => {
            if (!item.parentId) {
              item.children = []
              areaCodelistnew.push(item)
            }
          })
          areaCodelistnew.forEach((item1, index1) => {
            let info = areaCodelist.find((item2, index2) => {
              return item1.id === item2.parentId
            })
            if (info) {
              item1.children = []
              areaCodelist.forEach((item3, index3) => {
                if (item1.id === item3.parentId) {
                  item1.children.push(item3)
                }
              })
            } else {
              item1.children = null
            }
          })
          areaCodelistnew.forEach((item4, index4) => {
            if (item4.children) {
              item4.children.forEach((item5, index5) => {
                let info2 = areaCodelist.find((item6, index6) => {
                  return item5.id === item6.parentId
                })
                if (info2) {
                  item5.children = []
                  areaCodelist.forEach((item7, index7) => {
                    if (item5.id === item7.parentId) {
                      item5.children.push(item7)
                    }
                  })
                } else {
                  item5.children = null
                }
              })
            }
          })
          this.areaCodelist = areaCodelistnew
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 选择客户行政区划
     */
    customerareaCodesChange () {
      this.$refs['ref_customerareaCodes'].dropDownVisible = false
    },
    /**
     * 提交表单
     */
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          let params = this.ruleForm;
          if (this.isEdit) { // 修改
            return new Promise((resolve, reject) => {
              Customers.update(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加
            return new Promise((resolve, reject) => {
              Customers.add(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '添加成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
h3{border-bottom: 1px solid #E9E9EB;padding: 0 0 10px;}
.table_container{margin: 10px 0;}
.form-single-info{display: flex;justify-content: center;}
</style>
